import time
from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm

from dependencies import get_token_header, oauth2_scheme
from core.config import settings
from models import ZhanUser, ZhanEmailCode, ZhanFeedBack, ZhanToken
from schemas.user import UserRegister, EmailVerify, FeedBack, zhanuser_pydantic_model, ForgotPasswordRequest
from services.user_services.user import UserVerifyService
from dependencies import get_current_active_user
from services.emails.email_service import EmailService

router = APIRouter(
    prefix="/user",
    tags=["users"],
    # dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)


@router.post("/login/", tags=["users"])
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = await UserVerifyService.authenticate_user(form_data.username, form_data.password)
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = UserVerifyService.create_access_token(
        data={"sub": user.username, "pk": user.id, "now": int(time.time())}, expires_delta=access_token_expires
    )
    token = await ZhanToken.filter(user=user, token=access_token).first()
    if token:
        token.user = user
        token.token = access_token
        await token.save()
    else:
        await ZhanToken.create(user=user, token=access_token)
    return {"access_token": access_token, "token_type": "bearer"}


@router.get("/me", tags=["users"])
async def read_user_me(current_user: ZhanUser = Depends(get_current_active_user)):
    result = zhanuser_pydantic_model.from_orm(current_user)
    return result


@router.get("/send_code", tags=["users"])
async def send_code(email: str):
    await EmailService.verify_email_user(email)
    email_item = EmailVerify(email=email)
    await EmailService.send_email_code(email_item.email)
    return {"data": "success"}


@router.get("/forgot/send_code", tags=["users"])
async def send_code(email: str):
    await EmailService.verify_email_user_forgot(email)
    email_item = EmailVerify(email=email)
    await EmailService.send_email_code(email_item.email, ZhanEmailCode.EMAIL_TYPE_FORGOT)
    return {"data": "success"}


@router.post("/register", tags=["users"])
async def register(user_register: UserRegister):
    await EmailService.verify_email_user(user_register.username)
    await EmailService.verify_code(user_register.username, user_register.code)
    await EmailService.use_code(user_register.username)
    user = await ZhanUser.create(**user_register.dict())
    user.email = user_register.username
    user.password = UserVerifyService.get_password_hash(user.password)
    await user.save()
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = UserVerifyService.create_access_token(
        data={"sub": user.username, "pk": user.id, "now": int(time.time())}, expires_delta=access_token_expires
    )
    await ZhanToken.create(user=user, token=access_token)
    return {"access_token": access_token, "token_type": "bearer"}


# TODO 忘记密码的接口  退出登录
# 检查用户的密码加密方式
@router.get("/logout")
async def logout(current_user: ZhanUser = Depends(get_current_active_user)):
    token = await ZhanToken.filter(user=current_user).first()
    await token.delete()
    return {"data": "success"}


@router.post("/feedback")
async def feedback(feed_info: FeedBack):
    await ZhanFeedBack.create(**feed_info.dict())
    return {"data": "success"}


@router.post("/forgot_password")
async def forgot_password(request: ForgotPasswordRequest):
    user_item = await ZhanUser.filter(username=request.email).first()
    if not user_item:
        raise HTTPException(status_code=404, detail="Email not found")
    await EmailService.verify_code(request.email, request.code)
    user_item.password = UserVerifyService.get_password_hash(password=request.password)
    await user_item.save()
    await EmailService.use_code(request.email)
    return {"data": "success"}
